import 'package:ble_helper_plugin/library.dart';
import 'package:bluetooth_protocols_parser_plugin_example/extension.dart';
import 'package:flutter/material.dart';

import 'loading.dart';
import 'protocol_service.dart';
import 'routes.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<CustomScanResult> scanResults = [];

  // lorin协议
  bool isLorin = false;

  // 当前车辆
  CustomScanResult? _result;

  @override
  void initState() {
    super.initState();

    ProtocolService.to.init(isLorin: isLorin);

    ProtocolService.to.bluetoothConnectHelper.bluetoothConnectState
        .listen((event) {
      debugPrint('bluetoothConnectState: $event');
      // 判断App显示的页面是否当前页面
      if (event == CustomBluetoothConnectState.connected) {
        if (isLorin) {
          Navigator.pushNamed(context, AppRoutes.lorin);
        } else {
          Navigator.pushNamed(
            context,
            AppRoutes.huari,
            arguments: {"result": _result},
          );
        }
        Loading.showSuccess('连接成功');
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Protocols Tools'),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: scanResults.length,
              itemBuilder: (c, index) {
                CustomScanResult result = scanResults[index];
                return InkWell(
                  onTap: () {
                    Loading.show(null);
                    ProtocolService.to.bluetoothConnectHelper
                        .stopScan()
                        .then((value) {
                      _result = result;
                      return ProtocolService.to.bluetoothConnectHelper
                          .connect(result.device);
                    }).catchErrorHandler();
                  },
                  child: ListTile(
                    title: Text(result.advertisementData.advName),
                    subtitle: Text(_getSN(result)),
                  ),
                );
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  onPressed: () {
                    ProtocolService.to.bluetoothConnectHelper
                        .disconnect()
                        .then((value) {
                      ProtocolService.to.bluetoothConnectHelper.startScan(
                        callbackScanResults: (devices) {
                          setState(() {
                            scanResults = devices;
                          });
                        },
                      );
                    }).catchErrorHandler();
                  },
                  child: const Text('开始扫描'),
                ),
                ElevatedButton(
                  onPressed: () async {
                    await ProtocolService.to.bluetoothConnectHelper.stopScan();
                  },
                  child: const Text('停止扫描'),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 获取SN
  String _getSN(CustomScanResult result) {
    String sn = "";
    // 获取广播包数据
    List<int> manufacturerData =
        result.advertisementData.manufacturerData.values.firstOrNull ?? [];
    debugPrint(
        "${result.device.advName} => manufacturerData: $manufacturerData");
    // 假设SN在制造商特定数据中，具体格式取决于设备厂商
    if (manufacturerData.isNotEmpty) {
      // 解析SN - 这里需要根据设备的具体协议来解析
      int snLen = 6;
      if (manufacturerData.length >= snLen) {
        List<int> snBytes = manufacturerData.sublist(0, snLen);
        sn = snBytes
            .map((byte) => byte.toRadixString(16).padLeft(2, '0'))
            .join();
        debugPrint("${result.device.advName} => SN: $sn");
      }
    }
    return sn;
  }

  // 判断当前页面是否是活跃状态
  bool isCurrentPage() {
    if (!mounted) return false;
    final isCurrent = ModalRoute.of(context)?.isCurrent ?? false;
    if (!isCurrent) {
      debugPrint('Ignoring bluetooth state change as app is not on this page');
      return false;
    }
    return true;
  }
}
